﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CPPEI.Coolzon.DataProvider.Task
{
    public static class DataLoadTaskPool
    {
        private static Dictionary<string, DataLoadTask> s_taskPool = new Dictionary<string,DataLoadTask>();
        private static object s_lockObj = new object();

        public static DataLoadTask CreateTask(
            string userIdentity,
            Metadata.DataSource dataSource,
            Metadata.DataSet dataSet,
            List<QueryParameter> parameters,
            IDataProvider dataProvider)
        {
            string taskKey = GetTaskKeyString(dataSource, dataSet, parameters, dataProvider);

            DataLoadTask task = null;
            if (!s_taskPool.ContainsKey(taskKey))
            {
                lock (s_lockObj)
                {
                    if (!s_taskPool.ContainsKey(taskKey))
                    {
                        task = new DataLoadTask(taskKey, userIdentity, dataSource, dataSet, parameters, dataProvider);
                        s_taskPool.Add(taskKey, task);
                    }
                    else
                    {
                        task = s_taskPool[taskKey];
                    }
                }
            }
            else
            {
                task = s_taskPool[taskKey];
            }
            return task;
        }

        public static CPPEI.Coolzon.Data.DataResult Run(DataLoadTask task)
        {
            task.Ref();
            task.Run();
            task.Release();
            if (task.IsCanDispose())
            {
                lock (s_lockObj)
                {

                    //Common.Logger.Debug("data task key:[{0}] remove from taskpool", task.Key);
                    s_taskPool.Remove(task.Key);
                }
            }
            return task.DataResult;
        }

        private static string GetTaskKeyString(Metadata.DataSource dataSource,
            Metadata.DataSet dataSet,
            List<QueryParameter> parameters,
            IDataProvider dataProvider)
        {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.AppendFormat("source={0},set={1},", dataSource.Name, dataSet.Name);
            for (int index = 0; index < parameters.Count; index++)
            {
                stringBuilder.AppendFormat(",{0}={1}", parameters[index].Name, parameters[index].ValueString);
            }
            return stringBuilder.ToString();
        }
    }
}
